/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.gwxs;

import cn.ac.iie.di.datadock.rdata.exchange.client.v1.session.RESendSession;
import cn.ac.iie.di.global.GlobalParas;
import cn.ac.iie.di.tools.MMUrlPath;
import cn.ac.iie.di.gwxs.JsonGwxSender.SessionPool;
import static cn.ac.iie.di.server.GwxParserStartup.errorLogger;
import cn.ac.iie.di.tools.GenerateMD5;
import cn.ac.iie.di.tools.GetIpTools;
import cn.ac.iie.di.tools.TimeFormat;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.apache.log4j.Logger;
//import org.json.JSONException;
//import org.json.JSONObject;
//import org.json.JSONTokener;
//import org.json.XML;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.JSONObject;
import org.json.XML;

/**
 *
 * @author lenovo-pc
 */
public class JsonGwxTask4 implements Runnable {

    private final List<String> jsonList;

    static private final HashMap<String, String> JsonData;//存储Json中的数据
    static org.apache.log4j.Logger logger = null;

    static {
        logger = org.apache.log4j.Logger.getLogger(JsonGwxTask4.class.getName());
    }

    private SimpleDateFormat formatter;

    static {

        JsonData = new HashMap<>();

    }
    private final SessionPool pool;

    public JsonGwxTask4(List<String> jsonList, SessionPool pool) {
        this.jsonList = jsonList;
        this.pool = pool;
        this.formatter = new SimpleDateFormat("yyyy-MM");
    }

    @Override
    public void run() {
        RESendSession session = null;
        long line = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH");
        Set<String> cc = new HashSet<String>();
        long startTime = System.currentTimeMillis();
        HashMap<Long, Integer> occNum = new HashMap<Long, Integer>();
        try {
            session = pool.borrowSession();
            logger.debug("asdfzcvetqtert " + jsonList.size());
            for (String json : jsonList) {
                if (json != null && !json.isEmpty()) {
                    String[] xmls = json.split("</Msg>");
                    for (String xml : xmls) {
                        if (xml.trim().isEmpty()) {
                            continue;
                        }
                        try {
                            long s1 = System.currentTimeMillis();
                            JSONObject xmlJSONObj = XML.toJSONObject(xml + "</Msg>");
                            Boolean type5 = false;
                            JSONObject j = new JSONObject(xmlJSONObj.get("Msg").toString());
//                        Document document = DocumentHelper.parseText(json.replaceAll("[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]", ""));
//                        Element msg = document.getRootElement();
//                        List<Element> list = msg.elements();
//                        logger.info("Document time " + (System.currentTimeMillis() - s1));
                            if ("5".equals(j.getString("Type"))) {
                                type5 = true;
                            }
                            //g_id  MD5(根据FromUin+MsgID+Chatroom预处理)
                            String key = null;
                            if (type5) {
                                key = j.get("FromUin").toString() + j.get("FromTime").toString() + j.get("Chatroom").toString();
                            } else {
                                key = j.get("FromUin").toString() + j.get("MsgID").toString() + j.get("Chatroom").toString();
                            }

                            session.setString("g_id", GenerateMD5.string2MD5(key));
                            session.setString("g_ch_key", GenerateMD5.string2MD5(key));
                            session.setString("g_asp", "WeChat");
                            session.setString("g_adp", "WeChat");
                            if (j.get("FromTime").toString() != null && !j.get("FromTime").toString().trim().isEmpty()) {
                                Long pt = Long.valueOf(j.get("FromTime").toString());
                                session.setLong("m_publish_time", pt);
                                Long time = TimeFormat.getTime(pt);
//                            Long time = Long.valueOf(j.get("FromTime").toString().substring(0, j.get("FromTime").toString().length() - 2) + "00");
                                if (occNum.containsKey(time)) {
                                    occNum.put(time, occNum.get(time) + 1);
                                } else {
                                    occNum.put(time, 1);
                                }
                            } else {
                                session.setLong("m_publish_time", 0);
                            }
                            session.setLong("m_insert_time", -99);
                            session.setLong("m_chat_room", Long.valueOf(j.get("Chatroom").toString()));
                            if (type5) {
                                session.setString("m_ch_id", j.get("FromTime").toString());
                            } else {
                                session.setString("m_ch_id", j.get("MsgID").toString());
                            }

                            session.setInt("m_type", Integer.valueOf(j.get("Type").toString()));

                            if (type5) {
                                session.setString("m_content", j.get("Title").toString());
                            } else {
                                session.setString("m_content", j.get("Content").toString());
                            }

                            session.setString("m_language", "");
                            session.setString("u_g_ch_key", j.get("FromUin").toString());
                            session.setLong("u_ch_id", Long.valueOf(j.get("FromUin").toString()));
                            if (type5) {
                                session.setString("u_name", "");
                                session.setString("u_send_ip", "");
                                session.setInt("m_country_code", -1);
                                session.setInt("u_loc_county", -1);
                                session.setInt("u_loc_province", -1);
                                session.setInt("m_dom_for", 0);
                                session.setLong("m_mm_id", -1);
                            } else {
                                session.setString("u_name", j.get("From").toString());
                                session.setString("u_send_ip", j.get("ClientIP").toString());
//                        session.setString("u_send_ip", "未知");
//                        long s2 = System.currentTimeMillis();
                                int[] addrNum = GetIpTools.getIpAddr(j.get("ClientIP").toString());
                                //新加字段
                                int dom = 0;
                                if (addrNum[1] < 1000 && addrNum[1] > 100) {
                                    dom = -1;
                                    session.setInt("m_country_code", addrNum[1]);
                                    session.setInt("u_loc_county", -1);
                                    session.setInt("u_loc_province", -1);
//                            logger.info("ipipipipip" + addrNum[1] + msg.element("ClientIP").getText());
                                } else {
                                    dom = 1;
                                    session.setInt("m_country_code", 150);
                                    session.setInt("u_loc_county", addrNum[0]);
                                    session.setInt("u_loc_province", Integer.valueOf(addrNum[1] + "0000"));
                                }
//                        logger.info("Document time " + (System.currentTimeMillis() - s2));
                                session.setInt("m_dom_for", dom);
                                session.setLong("m_mm_id", Long.valueOf(j.get("MediaID").toString()));
                            }

                            int type = Integer.valueOf(j.get("Type").toString());
                            JSONObject arrStr = null;
                            JSONObject json1 = null;
                            switch (j.get("Type").toString()) {
                                case "43":
                                    arrStr = XML.toJSONObject(j.get("Content").toString());
                                    json1 = new JSONObject(arrStr.get("msg").toString());
                                    session.setStrings("m_mm_feature", new String[]{json1.get("videomsg").toString()});
                                    try {
                                        if (j.getString("MediaURL").trim().isEmpty()) {
                                            GlobalParas.videoCount.incrementAndGet();
                                        }
                                    } catch (Exception e) {
                                        errorLogger.error("the file no MediaURL: " + xml + "</Msg>" + " " + e, e);
                                    }
                                    break;
                                case "44":
                                    arrStr = XML.toJSONObject(j.get("Content").toString());
                                    json1 = new JSONObject(arrStr.get("msg").toString());
                                    session.setStrings("m_mm_feature", new String[]{json1.get("videomsg").toString()});
                                    try {
                                        if (j.getString("MediaURL").trim().isEmpty()) {
                                            GlobalParas.videoCount.incrementAndGet();
                                        }
                                    } catch (Exception e) {
                                        errorLogger.error("the file no MediaURL: " + xml + "</Msg>" + " " + e, e);
                                    }
                                    break;
                                case "34":
                                    arrStr = XML.toJSONObject(j.get("Content").toString());
                                    json1 = new JSONObject(arrStr.get("msg").toString());
                                    session.setStrings("m_mm_feature", new String[]{json1.get("voicemsg").toString()});
                                    try {
                                        if (j.getString("MediaURL").trim().isEmpty()) {
                                            GlobalParas.voiceCount.incrementAndGet();
                                        }
                                    } catch (Exception e) {
                                        errorLogger.error("the file no MediaURL: " + xml + "</Msg>" + " " + e, e);
                                    }
                                    break;
                                case "3":
                                    arrStr = XML.toJSONObject(j.get("Content").toString());
                                    json1 = new JSONObject(arrStr.get("msg").toString());
                                    session.setStrings("m_mm_feature", new String[]{json1.get("imgmsg").toString()});
                                    try {
                                        if (j.getString("MediaURL").trim().isEmpty()) {
                                            GlobalParas.imgCount.incrementAndGet();
                                        }
                                    } catch (Exception e) {
                                        errorLogger.error("the file no MediaURL: " + xml + "</Msg>" + " " + e, e);
                                    }
                                    break;
                                case "5":
                                    session.setStrings("m_mm_feature", new String[0]);
                                    try {
                                        if (j.getString("MediaURL").trim().isEmpty()) {
                                            GlobalParas.translateCount.incrementAndGet();
                                        }
                                    } catch (Exception e) {
                                        errorLogger.error("the file no MediaURL: " + xml + "</Msg>" + " " + e, e);
                                    }
                                    break;
                                default:
                                    session.setStrings("m_mm_feature", new String[0]);
                            }

                            session.setLongs("m_themes_list", new long[]{});
                            session.setLongs("m_topics_list", new long[]{});
                            session.setLongs("m_rules_list", new long[]{});
//                        session.setInt("m_msg_cnt", 0);
                            String[] time = new TimeFormat().getTimeString(Long.valueOf(j.get("FromTime").toString())).split("-");
                            session.setInt("m_year", Integer.valueOf(time[0]));
                            session.setInt("m_month", Integer.valueOf(time[1]));
                            session.setInt("m_day", Integer.valueOf(time[2]));
                            session.setInt("m_hour", Integer.valueOf(time[3]));
                            session.setString("m_mm_content", "");
                            try {
                                session.setString("m_mm_url", j.get("MediaURL").toString());
                            } catch (Exception e) {
                                session.setString("m_mm_url", "");
                            }

                            try {
                                session.add();
                                line++;
                            } catch (Exception e) {
                                sendMSG(session);
                                logger.info("GMSG successful send " + line);
                                line = 0;
                                session.add();
                                line++;
                            }

                        } catch (Exception ex) {
                            errorLogger.warn("The session add is wrong:" + ex + "error msg" + xml + "</Msg>", ex);
                        }
                    }
                }
            }
            sendMSG(session);
            long endTime = System.currentTimeMillis();
            logger.info("GMSG successful send " + line + " Send Time is " + (endTime - startTime));
            line = 0;
            Long tt = System.currentTimeMillis();
            GlobalParas.mapQueue.put(occNum);
            logger.debug("OccNum Size : " + occNum.size() + " content : " + occNum.toString());
            logger.debug("mapQueue put time : " + (System.currentTimeMillis() - tt));
            occNum = null;

        } catch (Exception ex) {
            errorLogger.error("know News Task error ", ex);
            ex.printStackTrace();
        } finally {
            if (session != null) {
                pool.returnSession(session);
            }
        }
    }

    public void sendMSG(RESendSession session) {
        while (true) {
            try {
                session.flush();
                break;
            } catch (Exception ex) {
                logger.info("what's up buddy ? how's it going ?" + ex, ex);
            }
        }
    }
}
